package com.nashuju.web.service.sys;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nashuju.web.dao.sys.SysFunctionDao;
import com.nashuju.web.entity.sys.SysFunction;
import com.nashuju.web.service.role.RolePermissionService;

@Service
public class SysFunctionService extends CrudService<SysFunction, SysFunctionDao> {

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 删除系统功能
     */
    @Override
    public void del(SysFunction sysFunction) {
        // 先删除角色
        rolePermissionService.delBySfId(sysFunction.getSfId());

        this.getDao().del(sysFunction);
    }

    /**
     * 通过资源ID查找系统功能
     * @param srId
     * @return
     */
    public List<SysFunction> getBySySResId(int srId) {
        ExpressionQuery query = ExpressionQuery.buildQueryAll();
        query.add(new ValueExpression("sr_id", srId));

        return find(query);
    }

    /**
     * 获取用户系统功能
     * @param username
     * @return
     */
    public List<SysFunction> getUserSysFunction(String username) {
        return this.getDao().findUserSysFunction(username);
    }

    public List<SysFunction> getByOperateCode(String operateCode) {
        ExpressionQuery query = ExpressionQuery.buildQueryAll();
        query.add(new ValueExpression("operate_code", operateCode));

        return find(query);
    }

    /**
     * 根据资源ID删除系统功能
     * @param srId
     */
    public void delBySrId(int srId) {
        List<SysFunction> sysFuncs = getBySrId(srId);
        for (SysFunction rSysFunction : sysFuncs) {
            del(rSysFunction);
        }
    }

    private List<SysFunction> getBySrId(int srId) {
        ExpressionQuery query = ExpressionQuery.buildQueryAll();
        query.add(new ValueExpression("sr_id", srId));

        return find(query);
    }

    public SysFunction getByOperateCodeSrId(String operateCode, int srId) {
        ExpressionQuery query = new ExpressionQuery();
        query.setLimit(1);
        query.add(new ValueExpression("operate_code", operateCode));
        query.add(new ValueExpression("sr_id", srId));

        List<SysFunction> list = find(query);

        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }

        return null;
    }

    public boolean isExistSysFun(String operateCode, int srId) {
        return this.getByOperateCodeSrId(operateCode, srId) != null;
    }
}
